package com.excel.anly.utils;

import com.excel.anly.entity.OutExcelQuery;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;

public class ExcelUtil {

    public static HSSFWorkbook exportExcel(String sheetName, List<String> titleList,
                                           List dataList) throws Exception {
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet(sheetName);
        HSSFRow titleRow = sheet.createRow(0);
        int titleSize = titleList.size();
        for (int i = 0; i < titleSize; i++) {
            titleRow.createCell(i).setCellValue(titleList.get(i));
        }
        int count = 0;
        int dataSize = dataList.size();
        for (int i = 0; i < dataSize; i++) {
            count++;
            HSSFRow rowData = sheet.createRow(i + 1);
            Class<?> aClass = dataList.get(i).getClass();
            Field[] fields = aClass.getDeclaredFields();
            for (int j = 0; j < fields.length; j++) {
                fields[j].setAccessible(true);
                rowData.createCell(j).setCellValue((String) fields[j].get(dataList.get(i)));

            }
        }
        return wb;
    }


    public static void getExcel(HttpServletResponse response) throws Exception {
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("sheet1");
        //创建第一行
        HSSFRow row1 = sheet.createRow(0);
        row1.createCell(0).setCellValue("账户");
        row1.createCell(1).setCellValue("用户名");
        row1.createCell(2).setCellValue("密码");
        row1.createCell(3).setCellValue("日期");
        //创建第二行
        HSSFRow row2 = sheet.createRow(1);
        row2.createCell(0).setCellValue("admin");
        row2.createCell(1).setCellValue("张三");
        row2.createCell(2).setCellValue("123456");
        row2.createCell(3).setCellValue(new Date());
        //创建第三行
        HSSFRow row3 = sheet.createRow(2);
        row3.createCell(0).setCellValue("ceshi");
        row3.createCell(1).setCellValue("李四");
        row3.createCell(2).setCellValue("123456");
        row3.createCell(3).setCellValue(new Date());
        ServletOutputStream outputStream = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename=demo.xls");
        response.setContentType("application/x-xls");
        wb.write(outputStream);
        outputStream.close();

    }
}